package com.cheer.ba.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.footview.CustomerFooter;
import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.listener.OnItemClickListener;
import com.cheer.ba.model.LookMyBillModel;
import com.cheer.ba.presenter.impl.CloudBookPresenter;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.adapter.FrequentlyAreaAdp;
import com.cheer.ba.view.adapter.LookMyBillAdp;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.cheer.lib_recycle_swipe.Closeable;
import com.cheer.lib_recycle_swipe.OnSwipeMenuItemClickListener;
import com.cheer.lib_recycle_swipe.SwipeMenu;
import com.cheer.lib_recycle_swipe.SwipeMenuCreator;
import com.cheer.lib_recycle_swipe.SwipeMenuItem;
import com.cheer.lib_recycle_swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;

/**
 * 描述 ：我的账本列表
 * 作者 ：hq
 * 时间 ：2017/5/19 16:38
 */
public class LookMyBillAty extends BaseCommAty {

    @BindView(R.id.id_comm_bill_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_comm_bill_recyclev)
    SwipeMenuRecyclerView mRecycleView;
    private LookMyBillAdp mMyBillAdp;
    private List<LookMyBillModel> mLookMyBills = new ArrayList<LookMyBillModel>();
    //记录从哪个界面进入
    private int page_from;
    //记录油卡id
    private String mCardId;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_look_my_bill, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return !mLookMyBills.isEmpty();
    }

    @Override
    public void initPresenter() {
        presenter = new CloudBookPresenter();
    }

    @Override
    public void initView() {
        page_from = getIntent().getIntExtra(IntentKey.General.KEY_PAGE, Constants.DEFAULTVALUE);
        if (page_from == IntentCode.General.JUMP_DEVICE) {
            //我的设备进入
            mCardId = getIntent().getStringExtra(IntentKey.General.KEY_ID);
            setTitleText("油卡变更记录");
        } else if (page_from == IntentCode.General.JUMP_QYE) {
            setTitleText("交易记录");
        } else if (page_from == IntentCode.General.JUMP_CLOUD) {
            //云记账
            setTitleText(getString(R.string.ic_cloud_record));
            setTitleIcon(R.drawable.ic_add_oil_card, false, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(aty, AddMyCloudBooks.class);
                    startActivityForResult(intent, IntentCode.Book.BOOK_REQUEST_CODE);
                }
            });
        } else if (page_from == IntentCode.General.JUMP_MONEY) {
            //提现记录
            setTitleText("提现记录");
        }
        setXRefreshView(mXRefreshView, true, true, false, false, new CheerHeadView(aty), new CustomerFooter(aty));
        mRecycleView.setLayoutManager(new LinearLayoutManager(aty));
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        // 设置菜单创建器。
        mRecycleView.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        mRecycleView.setSwipeMenuItemClickListener(menuItemClickListener);
        mRecycleView.smoothOpenRightMenu(0);
        mRecycleView.setNestedScrollingEnabled(false);

        mMyBillAdp = new LookMyBillAdp(mLookMyBills, page_from);
        mMyBillAdp.setOnItemClickListener(onItemClickListener);
        mRecycleView.setAdapter(mMyBillAdp);
    }

    @Override
    public void initData() {
        if (hasDataInPage()) {
            mXRefreshView.startRefresh();
        } else {
            loadData(true, false);
        }
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false, false);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                loadData(false, true);
            }
        });
    }

    /**
     * 加载数据
     *
     * @param loadMore
     */
    public void loadData(boolean isShowLoad, boolean loadMore) {
        if (page_from == IntentCode.General.JUMP_CLOUD) {
            //云记账
            ((CloudBookPresenter) presenter).searchMyBooks(isShowLoad, loadMore, "0", "", "");
        } else if (page_from == IntentCode.General.JUMP_DEVICE) {
            //我的设备
            ((CloudBookPresenter) presenter).getMyDevice(isShowLoad, loadMore, mCardId);
        } else if (page_from == IntentCode.General.JUMP_QYE) {
            //企业
            ((CloudBookPresenter) presenter).getMyTrades(isShowLoad, loadMore);
        }else if(page_from == IntentCode.General.JUMP_MONEY){
            //提现记录
            ((CloudBookPresenter) presenter).getMoneyRecords(isShowLoad, loadMore);
        }
        if (!loadMore) {
            stopRefresh(mXRefreshView, 2000);
        } else {
            stopLoadMore(mXRefreshView, 2000);
        }
    }


    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int size = getResources().getDimensionPixelSize(R.dimen.item_height);
            if (viewType == FrequentlyAreaAdp.VIEW_TYPE_NONE) {
                //不添加滑动
            } else {
                SwipeMenuItem addItem = new SwipeMenuItem(aty)
                        .setBackgroundDrawable(getResources().getDrawable(R.color.color_ff3b32))
//                .setImage(R.drawable.ic_home_msg)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setTextSize(16)
                        .setHeight(size)
                        .setWidth(size);
                swipeRightMenu.addMenuItem(addItem);
            }
        }
    };

    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView#RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            // 关闭被点击的菜单。
            closeable.smoothCloseMenu();
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                LookMyBillModel model = mMyBillAdp.getItem(adapterPosition);
                //右侧菜单
                if (menuPosition == 0) {
                    //删除
                    ((CloudBookPresenter) presenter).delMyBooks(model.uid);
                }
            }
        }
    };

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            LookMyBillModel model = mMyBillAdp.getItem(position);
            if (null != model) {
                Intent intent = new Intent(aty, DetailBooksAty.class);
                intent.putExtra(IntentKey.General.KEY_MODEL, model);
                showActivity(aty, intent);
            }
        }
    };

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
        if (!loadMore) {
            mLookMyBills.clear();
            mXRefreshView.stopRefresh();
        } else {
            mXRefreshView.stopLoadMore();
        }
        if (null != t) {
            if (TextUtils.equals(ConstantTag.SEARCH_MY_BOOK, tag) || TextUtils.equals(tag, ConstantTag.GET_MY_TRADE)) {
                //获得我的云记账
                List<LookMyBillModel> books = (List<LookMyBillModel>) t;
                if (books.isEmpty()) {
                    if (loadMore) {
                        ToastUtil.showToast(getString(R.string.no_more_data));
                    } else {
                        Session.setUserBooks(false);
                    }
                } else {
                    mLookMyBills.addAll(books);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handList();
                            mMyBillAdp.notifyDataSetChanged();
                        }
                    });
                }
            } else if (TextUtils.equals(tag, ConstantTag.SUGGEST_SUCCESS)) {
                //移除item成功
                mXRefreshView.startRefresh();
            }
        }
    }

    public void addModel(int pos, LookMyBillModel mModel) {
        LookMyBillModel mLook = new LookMyBillModel();
        mLook.month = mModel.month;
        mLook.createTime = mModel.createTime;
        mLookMyBills.add(pos, mLook);
    }

    /**
     * 处理list
     */
    public void handList() {
        Iterator<LookMyBillModel> it = mLookMyBills.iterator();
        while (it.hasNext()) {
            LookMyBillModel model = it.next();
            if (StringUtils.isEmpty(model.uid)) {
                it.remove();
            }
        }
        String today = StringUtils.getMonth(System.currentTimeMillis() + "");
        String recordMonth = "";

        List<Integer> mSavePos = new ArrayList<Integer>();
        List<LookMyBillModel> mSavePosModel = new ArrayList<LookMyBillModel>();
        int mSaveSize = mLookMyBills.size();

        for (int i = 0; i < mLookMyBills.size(); i++) {
            LookMyBillModel model = mLookMyBills.get(i);
            String m = StringUtils.getMonth(model.createTime);
            if (StringUtils.isEmpty(m)) {
                model.month = "";
            } else {
                if (TextUtils.equals(today, m)) {
                    model.month = "本";
                } else {
                    model.month = (Integer.parseInt(m) + 1) + "";
                }
            }
            if (!TextUtils.equals(recordMonth, model.month)) {
                recordMonth = model.month;
                mSavePos.add(i);
                mSavePosModel.add(model);
            }
        }
        for (int i = 0; i < mSavePos.size(); i++) {
            int m = mLookMyBills.size() - mSaveSize;
            int pos = mSavePos.get(i) + m;
            LookMyBillModel model = mSavePosModel.get(i);
            addModel(pos, model);
        }
        String a = mLookMyBills.get(0).month;
        for (int i = 1; i < mLookMyBills.size(); i++) {
            LookMyBillModel model = mLookMyBills.get(i);
            String m = model.month;
            if (TextUtils.equals(a, m)) {
                m = "";
            } else {
                a = m;
            }
            model.month = m;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentCode.Book.BOOK_REQUEST_CODE) {
            if (resultCode == IntentCode.Book.BOOK_RESULT_CODE) {
                //添加成功，刷新数据
                loadData(!hasDataInPage(), false);
            }
        }
    }
}
